<template>
	<view style="height: 100%;">
		<cu-custom :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">{{comment==null?'发表评论':'回复评论'}}</block>
		</cu-custom>
		<view class="container">
			<view v-if="comment!==null" class="bg-gray radius padding-sm" style="width: 100%;">
				<text
					class="text-grey padding-right-xs padding-bottom-xs">{{comment.author.nickname}}:</text>
				
				<view v-if="comment&&comment.content&&comment.content.length > 0">
					<text v-if="comment&&comment.content&&comment.content.length < 30" class="text-df text-black padding-bottom-sm" style="letter-spacing: 1.5upx;">
						{{comment.content}}
					</text>
					<view @tap.stop="expandComment" v-else-if="comment.is_expand==true" class="flex justify-start align-start" style="flex-direction: column;">
						<text class="action text-df text-black padding-bottom-sm" style="letter-spacing: 1.5upx;">
							{{comment.content}}
						</text>
						<text class="action text-blue text-sm">收起</text>
					</view>
					<text @tap.stop="expandComment" v-else class="action text-df text-black padding-bottom-sm" style="letter-spacing: 1.5upx;">
						{{comment.content.slice(0,29)}}...
						<text class="action text-blue text-sm">展开</text>
					</text>
				</view>
				
				<view v-if="comment.image_list && comment.image_list.length>0" style="width: 100%;">
					<view :style="'max-width:'+(comment.image_list.length>2?'50%;':'20%;')" :class="'grid flex-sub grid-square col-'+comment.image_list.length">
						<view class="bg-img" v-for="(url,index) in comment.image_list" :key="index"
							@tap="ViewCommentImage" :data-list="comment.image_list" :data-url="url">
							<image :src="url" mode="aspectFill"></image>
						</view>
					</view>
				</view>
			</view>
			<view style="height: 7px;"></view>
			<view class="tui-cells">
				<textarea @input="contentInput" class="tui-textarea" name="desc" placeholder="发表你的评论..." maxlength="500"
					placeholder-class="tui-phcolor-color" auto-focus />
				<view class="tui-textarea-counter">{{content.length}}/500</view>
			</view>
			<view  class="flex justify-start padding-top-sm" style="flex-wrap: wrap;">
				<view v-for="(item,index) in atUserList" :key="index">
					<view class="padding-left-sm padding-top-sm">
						<view @tap="jumpToUserProfile(item.user_id)" class="round cu-tag text-blue" style="background-color: #eff6fb;">
							@{{item.nickname}}
						</view>
					</view>
				</view>
			</view>
			<view class="flex align-center justify-start" style="width: 100%;">
				<view class="padding-right">
					<view class="tui-enclosure">
						<view class="action" @tap="ChooseImage">
							<tui-icon margin="0 40rpx 0 0" name="picture" :size="25"></tui-icon>
						</view>
						<view class="action" @tap="ChooseAtUser">
							<image src="../../static/images/setting/at.png" style="width: 56upx;height: 56upx;"></image>
						</view>
					</view>
				</view>
			</view>
			<view v-if="imgList.length>0">
				<view class="cu-form-group">
					<view class="grid col-4 grid-square flex-sub padding-bottom">
						<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="item.local">
							<image :class="(item.is_uping==false&&item.remote==null)||(item.is_uping==true)?'bg-mask':''" :src="item.local" mode="aspectFill"></image>
							<view class="cu-load load-cuIcon text-white padding-top" :class="item.is_uping?'loading':'over'"></view>
							<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
								<text class='cuIcon-close'></text>
							</view>
							<view v-if="item.is_uping==false&&item.remote==null">
								<view @click.stop="retryUpload(item,index)" style="position: absolute;z-index: 2;top: 40upx;right: 25upx;">
									<view class="flex justify-center align-center" style="flex-direction: column;">
										<text class="text-white sm">上传失败</text>
										<text class="text-white sm">点击重试</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="flex justify-center">
				<button @tap="commitAction" :class="'cu-btn round '+themeColor" style="width: 70%;">发表</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {chunk} from '@/api/utils.js'
	import {uploadImage,createComment,replyComment} from '@/api/api.js'
	export default {
		data() {
			return {
				atUserList:[],
				themeColor:this.ThemeColor,
				comment:null,
				postId:null,
				content:'',
				showLinkInput:false,
				imgList:[],
			};
		},
		computed: {
			showAtUsers() {
				let chunkList = chunk(this.atUserList,3)
				return chunkList
			}
		},
		onLoad(options) {
			this.postId = options.postId
			const eventChannel = this.getOpenerEventChannel()
			// 监听replyComment事件，获取上一页面通过eventChannel传送到当前页面的数据
			let that = this
			eventChannel.on('replyComment', function(data) {
				console.log(data)
			    that.comment = data
				that.comment.is_expand = false
			})
		},
		methods: {
			expandComment() 
			{
				this.comment.is_expand = !this.comment.is_expand
			},
			jumpToUserProfile(userId)
			{
				uni.navigateTo({
					url: '/pages/profile/profile?userId=' + userId
				})
			},
			ChooseAtUser() 
			{
				let that = this
				uni.navigateTo({
					url:'/pages/lessuse/at-user-choose/at-user-choose',
					success(res) {
						res.eventChannel.emit('passUserList', that.atUserList)
					},
					events:{
						finishChoose:function(data){
							that.atUserList = data
						}
					}
				})
			},
			retryUpload(item,index)
			{
				this.imgList[index].is_uping = true
				uploadImage(item.local, item.fileKey, (imgUrl) => {
					console.log(imgUrl)
					this.imgList[index].remote = imgUrl
					this.imgList[index].is_uping = false
				}, (error) => {
					this.imgList[index].is_uping = false
				})
			},
			commitAction() 
			{
				if(this.postId === null || this.postId === undefined) {
					uni.showToast({
						icon:'none',
						title:'postId非法!',
						duration:2000
					})
					return
				}
				if(this.content.length == 0 && this.imgList.length == 0) {
					uni.showToast({
						icon:'none',
						title:'内容和图片至少需要一种!',
					})
					return
				}
				let params = {}
				if(this.comment !== null) {
					params = {
						'commentId':this.comment.comment_id,
					}
				}else{
					params = {
						'postId':this.postId
					}
				}
				if(this.content.length > 0) {
					params['content'] = this.content
				}
				if(this.imgList.length > 0){
					let upImageList = [];
					this.imgList.forEach(item=>{
						if(item.remote !== null) {
							upImageList.push(item.remote)
						}
					})
					if(upImageList.length > 0) {
						params['imageList'] = upImageList
					}
				}
				if(this.atUserList.length > 0) {
					let atUserIds = []
					this.atUserList.forEach(item=>{
						atUserIds.push(item.user_id)
					})
					params['atUserList'] = atUserIds
				}
				uni.showLoading({
					title:'正在提交...'
				})
				if(this.comment !== null) {
					replyComment(params).then(res=>{
						uni.hideLoading()
						uni.$emit('CommentDetailNeedUpdate',{commentId:this.comment.comment_id})
						uni.$emit('PostNeedUpdateCommentList',{postId:this.comment.post_id})
						uni.showToast({
							title:'回复成功'
						})
						uni.navigateBack({
							delta:1
						})
					}).catch(error=>{
						uni.hideLoading()
					})
				}else{
					createComment(params).then(res=>{
						uni.hideLoading()
						uni.$emit('PostNeedUpdateCommentList',{postId:this.postId})
						uni.showToast({
							title:'评论成功'
						})
						uni.navigateBack({
							delta:1
						})
					}).catch(error=>{
						uni.hideLoading()
					})
				}
			},
			contentInput(e) 
			{
				this.content = e.detail.value
			},
			ChooseImage() {
				if(this.imgList.length >= 4) {
					uni.showToast({
						icon:'none',
						title:'最多上传四张'
					})
				}
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album','camera'], //从相册选择
					success: (res) => {
						let timestamp = new Date().getTime()
						let fileKey = String(timestamp)
						let item = {
							'local': res.tempFilePaths[0],
							'remote': null,
							'is_uping': false,
							'fileKey':fileKey,
						}
						this.imgList.push(item)
						let index = this.imgList.length - 1
						this.imgList[index].is_uping = true
						uploadImage(res.tempFilePaths[0], fileKey, (imgUrl) => {
							console.log(imgUrl)
							this.imgList[index].remote = imgUrl
							this.imgList[index].is_uping = false
						}).catch(error=>{
							this.imgList[index].is_uping = false
						})
					}
				});
			},
			ViewCommentImage(e) {
				console.log(e.currentTarget.dataset.list)
				console.log(e.currentTarget.dataset.url)
				uni.previewImage({
					urls: e.currentTarget.dataset.list,
					current: e.currentTarget.dataset.url
				});
			},
			ViewImage(e) {
				console.log(this.imgList)
				console.log(e.currentTarget.dataset.url)
				let previewImgList = []
				this.imgList.forEach(item=>{
					previewImgList.push(item.local)
				})
				uni.previewImage({
					urls: previewImgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
		}
	};
</script>

<style>
	page {
		background: #fff;
		color: #333;
	}

	.container {
		padding: 30rpx;
		box-sizing: border-box;
	}

	.tui-cells {
		border-radius: 4rpx;
		height: 280rpx;
		box-sizing: border-box;
		padding: 20rpx 20rpx 0 20rpx;
		position: relative;
	}

	.tui-cells::after {
		content: '';
		position: absolute;
		height: 200%;
		width: 200%;
		border: 1px solid #e6e6e6;
		transform-origin: 0 0;
		-webkit-transform-origin: 0 0;
		-webkit-transform: scale(0.5);
		transform: scale(0.5);
		left: 0;
		top: 0;
		border-radius: 8rpx;
		pointer-events: none;
	}

	.tui-textarea {
		height: 210rpx;
		width: 100%;
		color: #666;
		font-size: 28rpx;
	}

	.tui-phcolor-color {
		color: #ccc !important;
	}

	.tui-textarea-counter {
		font-size: 24rpx;
		color: #999;
		text-align: right;
		height: 40rpx;
		line-height: 40rpx;
		padding-top: 4rpx;
	}

	.tui-enclosure {
		display: flex;
		align-items: center;
		padding: 26rpx 10rpx;
		box-sizing: border-box;
	}

	.tui-cmt-btn {
		margin-top: 60rpx;
	}
</style>
